<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI VTuber - Live2D 渲染器（本地版）</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        
        body {
            background-color: #00FF00;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        
        #status {
            position: absolute;
            top: 10px;
            left: 10px;
            color: white;
            background: rgba(0, 0, 0, 0.7);
            padding: 10px 15px;
            border-radius: 5px;
            font-size: 14px;
            z-index: 1000;
        }
        
        #debug-info {
            position: absolute;
            top: 10px;
            right: 10px;
            color: white;
            background: rgba(0, 0, 0, 0.7);
            padding: 10px 15px;
            border-radius: 5px;
            font-size: 12px;
            font-family: monospace;
            z-index: 1000;
        }
        
        .status-ok { color: #00ff00; }
        .status-error { color: #ff0000; }
        .status-warning { color: #ffff00; }
        
        canvas {
            display: block;
        }
    </style>
</head>
<body>
    <div id="status">正在加载...</div>
    <div id="debug-info"></div>

    <!-- 使用本地库文件 -->
    <script src="/libs/pixi.min.js"></script>
    <script src="/libs/live2dcubismcore.min.js"></script>
    
    <script>
        // 全局变量
        let app;
        let canvas;
        let ws;
        let reconnectTimer;
        const WS_URL = 'ws://localhost:8765';
        
        // 状态显示
        const statusEl = document.getElementById('status');
        const debugEl = document.getElementById('debug-info');
        
        function updateStatus(message, type = 'ok') {
            statusEl.innerHTML = `<span class="status-${type}">${message}</span>`;
            console.log(`[${type.toUpperCase()}] ${message}`);
        }
        
        function updateDebugInfo(info) {
            const lines = [
                `PIXI版本: ${PIXI.VERSION}`,
                `Live2D Core: ${typeof Live2DCubismCore !== 'undefined' ? '已加载' : '未加载'}`,
                `WebSocket: ${ws?.readyState === 1 ? '已连接' : '未连接'}`,
                `嘴巴张度: ${(info.mouthOpen || 0).toFixed(2)}`,
                `情感: ${info.emotion || 'neutral'}`,
                `头部角度X: ${(info.angleX || 0).toFixed(1)}°`,
                `头部角度Y: ${(info.angleY || 0).toFixed(1)}°`
            ];
            debugEl.innerHTML = lines.join('<br>');
        }
        
        // 初始化 PIXI 应用
        async function initApp() {
            try {
                updateStatus('初始化渲染引擎...', 'warning');
                
                // 检查 PIXI.js 是否加载
                if (typeof PIXI === 'undefined') {
                    throw new Error('PIXI.js 未加载');
                }
                
                console.log('PIXI 版本:', PIXI.VERSION);
                console.log('Live2D Core:', typeof Live2DCubismCore !== 'undefined' ? '已加载' : '未加载');
                
                app = new PIXI.Application({
                    width: window.innerWidth,
                    height: window.innerHeight,
                    backgroundColor: 0x00FF00,
                    backgroundAlpha: 1,
                    antialias: true,
                    autoDensity: true,
                    resolution: window.devicePixelRatio || 1
                });
                
                document.body.appendChild(app.view);
                
                // 窗口大小调整
                window.addEventListener('resize', () => {
                    app.renderer.resize(window.innerWidth, window.innerHeight);
                });
                
                updateStatus('✓ 渲染引擎初始化完成，但Live2D模型加载需要完整SDK', 'warning');
                
                // 显示提示信息
                const text = new PIXI.Text(
                    '⚠ 使用简化渲染模式\\n\\n' +
                    '由于 pixi-live2d-display 库无法加载，\\n' +
                    '当前仅显示基础渲染画面。\\n\\n' +
                    'WebSocket 连接正常，可接收参数。\\n\\n' +
                    '建议：访问 web_live2d_offline.html 查看模型图片',
                    {
                        fontFamily: 'Microsoft YaHei',
                        fontSize: 20,
                        fill: 0xffffff,
                        align: 'center'
                    }
                );
                
                text.anchor.set(0.5);
                text.x = app.screen.width / 2;
                text.y = app.screen.height / 2;
                
                app.stage.addChild(text);
                
                connectWebSocket();
                
            } catch (error) {
                updateStatus(`✗ 初始化失败: ${error.message}`, 'error');
                console.error('初始化错误:', error);
            }
        }
        
        // 参数
        let currentParams = {
            mouthOpen: 0,
            emotion: 'neutral',
            angleX: 0,
            angleY: 0
        };
        
        // WebSocket 连接
        function connectWebSocket() {
            try {
                updateStatus('正在连接 WebSocket...', 'warning');
                
                ws = new WebSocket(WS_URL);
                
                ws.onopen = () => {
                    updateStatus('✓ WebSocket 已连接（简化模式）', 'ok');
                    clearTimeout(reconnectTimer);
                };
                
                ws.onmessage = (event) => {
                    try {
                        const data = JSON.parse(event.data);
                        
                        if (data.type === 'update_params') {
                            currentParams = { ...currentParams, ...data.params };
                            updateDebugInfo(currentParams);
                        }
                        
                    } catch (error) {
                        console.error('消息解析错误:', error);
                    }
                };
                
                ws.onerror = (error) => {
                    updateStatus('✗ WebSocket 错误', 'error');
                    console.error('WebSocket 错误:', error);
                };
                
                ws.onclose = () => {
                    updateStatus('⚠ WebSocket 已断开，5秒后重连...', 'warning');
                    reconnectTimer = setTimeout(connectWebSocket, 5000);
                };
                
            } catch (error) {
                updateStatus(`✗ WebSocket 连接失败: ${error.message}`, 'error');
                reconnectTimer = setTimeout(connectWebSocket, 5000);
            }
        }
        
        // 启动
        window.addEventListener('load', () => {
            // 检查库是否加载
            if (typeof PIXI === 'undefined') {
                updateStatus('✗ PIXI.js 加载失败', 'error');
                return;
            }
            
            if (typeof Live2DCubismCore === 'undefined') {
                console.warn('Live2D Cubism Core 未加载');
            }
            
            initApp();
        });
    </script>
</body>
</html>
